package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.controller.MobileAppVersionController
import com.zxy.supplier_system.server.entity.MobileAppVersion
import com.zxy.supplier_system.server.repository.MobileAppVersionRepository
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.server.ResponseStatusException

@Service
class MobileAppVersionService(
    private val mobileAppVersionRepository: MobileAppVersionRepository,
    private val employeeService: EmployeeService
) {

    @Transactional(readOnly = true)
    fun getLatest(clientVersionString: String): MobileAppVersionController.VersionResponse? {
        val requiredCurrentEmployee = employeeService.getRequiredCurrentEmployee()
        val clientVersion = try {
            MobileAppVersion.Version.fromVersionString(clientVersionString)
        } catch (e: Exception) {
            throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid client version")
        }

        val versions = this.mobileAppVersionRepository.findLatestVersionsAfter(clientVersion)
        if (versions.isNotEmpty()) {
            val updateNotes = versions.reversed().flatMap {
                it.updateNotes.filter { note ->
                    note.relatedAuthorities.any { authority ->
                        requiredCurrentEmployee.authorities.contains(authority)
                    }
                            || note.relatedAuthorities.isEmpty()
                }
            }.map { it.content }
            return if (updateNotes.isEmpty()){
                null
            }else{
                MobileAppVersionController.VersionResponse(
                    versions[0].version.toString(),
                    updateNotes
                )
            }
        }else{
            return null
        }
    }

}